package com.sisgh.jefdv1.core.jdbc.db;

import com.sisgh.jefdv1.util.StringUtils;
import lombok.Getter;

import java.sql.SQLException;
import java.util.regex.Pattern;

/**
 * 数据库枚举
 */
@Getter
public enum Database {
    // jdbc:mysql://localhost:3306/ms?serverTimezone=Asia/Shanghai
    MYSQL("mysql", "com.mysql.cj.jdbc.Driver",
            "jdbc:mysql://([a-zA-Z0-9.-]+)(:\\d+)/([a-zA-Z0-9_]+)",
            "jdbc:mysql://"),
    POSTGRESQL("postgresql","org.postgresql.Driver",
            null, null),
    ORACLE("oracle","oracle.jdbc.driver.OracleDriver",
            null, null),
    SQLSERVER("sqlserver","com.microsoft.sqlserver.jdbc.SQLServerDriver",
            null, null),
    ;

    // 名称
    private final String name;
    // 驱动类
    private final String driverName;
    // 正则表达式
    private final String pattern;
    // url 前缀
    private final String urlPrefix;

    Database(String name, String driverName, String pattern, String urlPrefix) {
        this.name = name;
        this.driverName = driverName;
        this.pattern = pattern;
        this.urlPrefix = urlPrefix;
    }

    public String buildUrl(String host, String port, String database) throws SQLException {
        String url = urlPrefix + host + ":" + port + "/" + database;

        if (!Pattern.matches(pattern, url)) {
            throw new SQLException("非法的 URL: " + url);
        }

        return url;
    }
}
